<template>
  <ex-dialog width="950px" class="ex-diolog" :title="title" :visible="visible" @closeDialog="handleClose">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="奖品图片" prop="img" v-if="ruleForm.type == 1||ruleForm.type == 3">
        <el-upload class="avatar-uploader2" :action="action" :show-file-list="false" :on-success="imgSuccess"
           :on-error="onError" :on-progress="onProgress" :multiple="false">
          <img class="banner_img" :src="ruleForm.img" alt="" v-if="ruleForm.img">
          <i class="el-icon-plus" style="font-size: 28px" v-else v-loading="imgLoading"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="奖品类型" prop="type">
        <el-select v-model="ruleForm.type" placeholder="选择奖品类型" autocomplete="off" :disabled="disabled">
          <el-option v-for="item in typeList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="权益名称" prop="businessId" v-if="ruleForm.type == 3">
        <el-select v-model="ruleForm.businessId" filterable placeholder="请选择" autocomplete="off">
          <el-option v-for="item in equityNameLs" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="奖品等级" prop="level">
        <el-select v-model="ruleForm.level" filterable placeholder="选择奖品等级" autocomplete="off">
          <el-option v-for="item in levelTypeList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="奖品名称" prop="name" v-if="ruleForm.type == 1">
        <el-input type="text" v-model="ruleForm.name" autocomplete="off" placeholder="请输入奖品名称"></el-input>
      </el-form-item>
      <el-form-item label="奖品价值" prop="worth" v-if="ruleForm.type == 1||ruleForm.type == 3">
        <el-input type="text" v-model="ruleForm.worth" autocomplete="off" placeholder="请输入奖品价值">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="有效期" prop="validity" v-if="ruleForm.type == 1||ruleForm.type == 3">
        <el-input type="text" v-model="ruleForm.validity" autocomplete="off" placeholder="请输入有效期内容"></el-input>
      </el-form-item>
      <el-form-item label="奖品数量" prop="amount" v-if="ruleForm.type == 1||ruleForm.type == 3">
        <el-input type="text" :disabled="disabled" v-model="ruleForm.amount" autocomplete="off" placeholder="请输入奖品数量">
        </el-input>
      </el-form-item>
      <el-form-item label-width="140px" label="选择数字权益卡" prop="businessId" v-if="ruleForm.type == 2">
        <el-select :disabled="disabled" filterable v-model="ruleForm.businessId" placeholder="选择奖品等级"
          autocomplete="off">
          <el-option v-for="item in businessList" :key="item.cardId" :label="item.cardName" :value="item.cardId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="奖品详情：" prop="detail">
        <div class="richText">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
          <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.detail" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="onCreated" @onChange="onChange" />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="sumitLoading">确认</el-button>
        <el-button @click="handleClose('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </ex-dialog>
</template>
<script>
  // components
  import Loading from '@/components/Loading/index'
  // api
  import {
    adminDict,
    cardList,
    addBoxPrize,
    editBoxPrize,
    detail,
    inventorySelect,
  } from '@/api/blindBox/boxSet'
  import '@wangeditor/editor/dist/css/style.css'
  import {
    Editor,
    Toolbar
  } from "@wangeditor/editor-for-vue";

  export default {
    components: {
      Loading,
      Editor,
      Toolbar
    },
    props: {
      visible: Boolean,
      id: String,
      path: String
    },
    data() {

      return {
        title: '新增盲盒奖品',
        roleList: [],
        action: process.env.VUE_APP_BASE_API + "/common/v1/upload",
        imgLoading: false,
        disabled: false,
        sumitLoading: false,
        typeList: [],
        levelTypeList: [], //奖品等级
        equityNameLs: [], //权益名称数组
        businessList: [], //数字权益卡列表
        ruleForm: {
          id: '',
          amount: '', //奖品数量
          businessId: '', //奖品业务id（权益卡id等）
          img: '', //奖品图片
          level: '', //	奖品等级;1-5级字典
          name: '', //奖品名称
          type: '1', //	奖品类型;1实物 2权益卡 3:权益库存
          validity: '', //有效期
          worth: '', //奖品价值
          detail: '',
        },
        rules: {
          amount: [{
            required: true,
            message: '请输入',
            trigger: ['blur','change']
          }],
          businessId: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }],
          img: [{
            required: true,
            message: '请上传图片',
            trigger: 'blur'
          }],
          level: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }],
          name: [{
            required: true,
            message: '请输入',
            trigger: ['blur','change']
          }],
          type: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }],
          validity: [{
            required: true,
            message: '请输入',
            trigger: ['blur','change']
          }],
          worth: [{
            required: true,
            message: '请输入',
            trigger: ['blur','change']
          }],
          detail: [{
            required: false,
            message: '请填写奖品详情',
            trigger: ['blur','change']
          }],
        },
        // 富文本配置
        logoUploadUrlImg: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //图片接口
        videoUploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //视频接口
        editor: null,
        html: "<p>hello&nbsp;world</p>",
        toolbarConfig: {
          // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
          // excludeKeys: [ /* 隐藏哪些菜单 */ ],
          excludeKeys: ['group-video']
        },
        editorConfig: {

          placeholder: "请输入内容...",
          // autoFocus: false,
          // 所有的菜单配置，都要在 MENU_CONF 属性下
          MENU_CONF: {},
        },
        mode: 'default', // or 'simple'

      }
    },
    computed: {

    },
    created() {
      var _this = this
      // 配置上传图片
      var name = ''
      this.editorConfig.MENU_CONF['uploadImage'] = {
        server: _this.logoUploadUrlImg,
        // headers: _this.headers,
        fieldName: 'file',
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        onSuccess(file, res) {
          name = file.name
          // console.log(`${file.name} 上传成功`, res)
        },
        customInsert(res, insertFn) {
          console.log(res)
          insertFn(res.result.url, name, res.result.url)
        }
      }
      // 配置上传视频
      this.editorConfig.MENU_CONF['uploadVideo'] = {
        server: _this.videoUploadUrl,
        // headers: _this.headers,
        fieldName: 'file',
        maxFileSize: 500 * 1024 * 1024,
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        customInsert(res, insertFn) {
          // res 即服务端的返回结果
          // 从 res 中找到 url ，然后插入
          insertFn(res.result.url)
        },
      }
      this.getadminDict()
      this.getInventorySelect()
      if (this.path == 'edit') {
        this.ruleForm.id = this.id
        this.disabled = true
        this.getDetail()
        this.title = '编辑盲盒奖品'
      } else {
        this.getCardList()
      }

    },
    methods: {
      onCreated(editor) {
        this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
        console.log('this.editor', this.editor)
      },
      onChange(editor) {
        console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
      },
      getEditorText() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getText()); // 执行 editor API
      },
      printEditorHtml() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getHtml()); // 执行 editor API
      },
      getadminDict() {
        //获取类型字典
        const params = {
          dictType: "box_prize_level,box_prize_type",
        };
        adminDict(params).then((res) => {
          this.levelTypeList = res.result[0].dictList;
          this.typeList = res.result[1].dictList;
        });
      },
      getInventorySelect() { //获取权益名称
        const params = {
          type: ""
        };
        inventorySelect(params).then((res) => {
          this.equityNameLs = res.result
        });
      },
      //获取数字权益卡列表
      getCardList() {
        var params = {
          cardId: this.ruleForm.businessId
        }
        cardList(params).then((res) => {
          this.businessList = res.result;
        });
      },
      getDetail() {
        var id = this.id
        detail(id).then(res => {
          var data = res.result
          this.ruleForm = res.result
          this.ruleForm.detail = res.result.detail
          this.getCardList()
        }).finally(() => {

        })
      },
      imgSuccess(res, file) { //文件上传成功时
        console.log(res.result.url)
        this.ruleForm.img = res.result.url
        this.$refs.ruleForm.validateField('img')
        this.imgLoading = false
      },
      onProgress(file) { //文件上传时
        this.imgLoading = true
      },
      onError(file) {
        this.imgLoading = false
      },
      //确认提交
      submitForm(formName) {
        console.log('formName', formName)
        this.$refs[formName].validate((valid) => {
          console.log('valid', valid)
          if (valid) {
            this.sumitLoading = true
            if (this.path == 'add') {
              var data = {
                ...this.ruleForm
              }
              console.log('data', data)
              addBoxPrize(data).then(res => {
                this.handleSuccess("创建成功")
                setTimeout(()=>{
                  this.sumitLoading = false
                },1000)
              }).catch(() => {
                this.loading = false
                this.sumitLoading = false
              })
            } else if (this.path == 'edit') {
              var data = {
                ...this.ruleForm
              }
              editBoxPrize(data).then(res => {
                this.handleSuccess("操作成功")
                setTimeout(()=>{
                  this.sumitLoading = false
                },1000)
              }).catch(() => {
                this.loading = false
                this.sumitLoading = false
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      //取消
      handleClose(formName) {
        this.$emit('update:visible', false)
        this.$refs[formName].resetFields();
      },
      //确认
      handleConfirm() {
        this.$emit('success', '你好')
      },
      handleSuccess(msg) {
        if (msg === '已拒绝') {
          var type = 'error'
        } else {
          var type = 'success'
        }
        this.$message({
          message: msg,
          type: type,
          duration: 1500,
          onClose: () => {
            this.handleClose('ruleForm')
            this.$emit('success')
          }
        })
      },
    }
  }

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  ::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .avatar-uploader2 {
    width: 130px;
    height: 130px;
    text-align: center;
    line-height: 130px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
  }

  .banner_img {
    width: 130px;
    height: 130px;
  }

  .el-input {
    width: 400px;
  }

  .richText {
    border: 1px solid #ccc;
    line-height: normal;
  }

</style>
